﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using System.Reflection;
using DevExpress.XtraEditors;

namespace QL_Truong_Hoc.HocTap
{
    public partial class frmDSThiTotNghiep : DevExpress.XtraEditors.XtraForm
    {
        private const string mcstrRoleCode = "thi_cu";

        private int mintKdtID;
        private int mintLopID;
        private int mintMonID;
        private int mintTtnID;
        private int mintTrinhDo;

        private string mstrKhoa;
        private string mstrKhoas;
        private string mstrMon;
        private string mstrLop;
        private string mstrNghe;
        private clsEnum.LAN_THI memLanThi;
        private bool mblnIsValid = false;

        private List<DevExpress.XtraGrid.StyleFormatCondition> mlstStyle;

        public frmDSThiTotNghiep()
        {
            InitializeComponent();
            mlstStyle = new List<DevExpress.XtraGrid.StyleFormatCondition>();
        }

        private void frmDSThiHetMon_Load(object sender, EventArgs e)
        {
            if (!clsCommon.fncCheckRole(Program.glstRoles, mcstrRoleCode))
            {
                this.BeginInvoke(new MethodInvoker(this.Close));
                return;
            }

            // TODO: This line of code loads data into the 'qLTHDataSet.mNghe' table. You can move, or remove it, as needed.
            this.mNgheTableAdapter.Fill(this.qLTHDataSet.mNghe);
            // TODO: This line of code loads data into the 'qLTHDataSet.mMonTotNghiep' table. You can move, or remove it, as needed.
            this.mMonTotNghiepTableAdapter.Fill(this.qLTHDataSet.mMonTotNghiep);
            // TODO: This line of code loads data into the 'qLTHDataSet.usrProc_GetThiTotNghiepFull' table. You can move, or remove it, as needed.
            this.usrProc_GetThiTotNghiepFullTableAdapter.Fill(this.qLTHDataSet.usrProc_GetThiTotNghiepFull);
            // TODO: This line of code loads data into the 'qLTHDataSet.mKhoa' table. You can move, or remove it, as needed.
            this.mKhoaTableAdapter.Fill(this.qLTHDataSet.mKhoa);
            // TODO: This line of code loads data into the 'qLTHDataSet.mGioiTinh' table. You can move, or remove it, as needed.
            this.mGioiTinhTableAdapter.Fill(this.qLTHDataSet.mGioiTinh);
            // TODO: This line of code loads data into the 'qLTHDataSet.mTrinhDoDaoTao' table. You can move, or remove it, as needed.
            this.mTrinhDoDaoTaoTableAdapter.Fill(this.qLTHDataSet.mTrinhDoDaoTao);
            // TODO: This line of code loads data into the 'qLTHDataSet.mMon' table. You can move, or remove it, as needed.
            this.mMonTableAdapter.Fill(this.qLTHDataSet.mMon);
            // TODO: This line of code loads data into the 'qLTHDataSet.mKhoaHoc' table. You can move, or remove it, as needed.
            this.mKhoaHocTableAdapter.Fill(this.qLTHDataSet.mKhoaHoc);
            // TODO: This line of code loads data into the 'qLTHDataSet.mLop' table. You can move, or remove it, as needed.
            this.mLopTableAdapter.Fill(this.qLTHDataSet.mLop);
            // TODO: This line of code loads data into the 'qLTHDataSet.mLanThi' table. You can move, or remove it, as needed.
            this.mLanThiTableAdapter.Fill(this.qLTHDataSet.mLanThi);

            mlstStyle.Add(dgvDanhSachHocSinh.FormatConditions[0]);
            mlstStyle.Add(dgvDanhSachHocSinh.FormatConditions[1]);
        }

        private void mniAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                using (frmThiTotNghiepNghe frmThemMoi = new frmThiTotNghiepNghe())
                {
                    frmThemMoi.ShowDialog();
                    if (!frmThemMoi.Changed) return;

                    this.usrProc_GetThiTotNghiepFullTableAdapter.Fill(this.qLTHDataSet.usrProc_GetThiTotNghiepFull);
                }
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void btnThemHs_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (mintTtnID <= 0) return;

                bool blnSuccess = true;
                int intHsID;
                List<int> lstExcept = new List<int>();

                for (int i = 0; i <= dgvDanhSachHocSinh.RowCount - 1; i++)
                {
                    intHsID = clsCommon.fncCnvNullToInt(dgvDanhSachHocSinh.GetRowCellValue(i, colHS_ID));
                    lstExcept.Add(intHsID);
                }

                //if (mintMonID <= 0) return;
                using (frmChonHsThiHetMon frmChon = new frmChonHsThiHetMon(mintMonID, mintLopID, mintKdtID, lstExcept, mstrMon, mstrLop, memLanThi))
                {
                    frmChon.ShowDialog();
                    if (frmChon.DanhSachChon.Count <= 0) return;

                    //thêm vào danh sách
                    DTO.TThiTotNghiepHocSinhDTO objThiTotNghiep = new DTO.TThiTotNghiepHocSinhDTO();
                    objThiTotNghiep.TTN_ID = mintTtnID;
                    
                    Program.gobjTrans = Program.gobjConn.BeginTransaction();

                    for (int i = 0; i <= frmChon.DanhSachChon.Count - 1; i++)
                    {
                        objThiTotNghiep.HS_ID = frmChon.DanhSachChon[i];
                        blnSuccess = blnSuccess && DAO.TThiTotNghiepHocSinhDAO.Insert(Program.gobjDb, Program.gobjTrans, objThiTotNghiep);
                    }

                    if (blnSuccess)
                    {
                        Program.gobjTrans.Commit();
                        this.usrProc_GetDanhSachThiTotNghiepTableAdapter.Fill(this.qLTHDataSet.usrProc_GetDanhSachThiTotNghiep, mintTtnID);
                        dgvDanhSachHocSinh.BestFitColumns();
                    }
                    else
                    { Program.gobjTrans.Rollback(); }
                }
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void grdControlDsDotThi_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (dgvDsDotThi.FocusedRowHandle < 0) return;

                mintKdtID = clsCommon.fncCnvNullToInt(dgvDsDotThi.GetFocusedRowCellValue(colKDT_ID));
                mintLopID = clsCommon.fncCnvNullToInt(dgvDsDotThi.GetFocusedRowCellValue(colLop_ID));
                mintMonID = clsCommon.fncCnvNullToInt(dgvDsDotThi.GetFocusedRowCellValue(colMTN_ID));
                mintTtnID = clsCommon.fncCnvNullToInt(dgvDsDotThi.GetFocusedRowCellValue(colTTN_ID));
                mintTrinhDo = clsCommon.fncCnvNullToInt(dgvDsDotThi.GetFocusedRowCellValue(colTD_ID));

                mstrKhoa = clsCommon.fncCnvNullToString(dgvDsDotThi.GetFocusedRowCellDisplayText(colKH_ID));
                mstrKhoas = clsCommon.fncCnvNullToString(dgvDsDotThi.GetFocusedRowCellDisplayText(colKHS_ID));
                mstrMon = clsCommon.fncCnvNullToString(dgvDsDotThi.GetFocusedRowCellDisplayText(colMTN_ID));
                mstrLop = clsCommon.fncCnvNullToString(dgvDsDotThi.GetFocusedRowCellDisplayText(colLop_ID));
                mstrNghe = clsCommon.fncCnvNullToString(dgvDsDotThi.GetFocusedRowCellDisplayText(colNG_ID));
                memLanThi = (clsEnum.LAN_THI)clsCommon.fncCnvNullToInt(dgvDsDotThi.GetFocusedRowCellValue(colLanThi_ID));

                //ẩn cột điểm lần 2 nếu đang là lần 1
                if (memLanThi == clsEnum.LAN_THI.LAN_1)
                {
                    colDiemLan2.Visible = false;
                    dgvDanhSachHocSinh.FormatConditions.Clear();
                    dgvDanhSachHocSinh.FormatConditions.Add(mlstStyle[0]);
                }
                else
                {
                    colDiemLan2.Visible = true;
                    dgvDanhSachHocSinh.FormatConditions.Clear();
                    dgvDanhSachHocSinh.FormatConditions.Add(mlstStyle[1]);
                }

                this.usrProcGetDanhSachThiTotNghiepBindingSource.Filter = string.Format("MTN_ID = {0}", mintMonID);
                this.usrProc_GetDanhSachThiTotNghiepTableAdapter.Fill(this.qLTHDataSet.usrProc_GetDanhSachThiTotNghiep, mintTtnID);
                dgvDanhSachHocSinh.BestFitColumns();

                grpDanhSachThiSinh.Text = "Danh sách thí sinh thi hết môn " + mstrMon + " - lớp " + mstrLop + " - khóa " + mstrKhoas + " - khoa " + mstrKhoa;
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void btnSuaDiem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                dgvDanhSachHocSinh.FocusedRowHandle = 0;

                switch (memLanThi)
                {
                    case clsEnum.LAN_THI.LAN_1:
                        colDiemLan1.OptionsColumn.AllowEdit = true;
                        dgvDanhSachHocSinh.FocusedColumn = colDiemLan1;
                        //dgvDanhSachHocSinh.SelectCells(0, colHSM_diemketthucmodulelan1, 0, colHSM_diemketthucmodulelan1);
                        break;
                    case clsEnum.LAN_THI.LAN_2:
                        colDiemLan2.OptionsColumn.AllowEdit = true;
                        dgvDanhSachHocSinh.FocusedColumn = colDiemLan2;
                        //dgvDanhSachHocSinh.SelectCells(0, colHSM_diemketthucmodulelan2, 0, colHSM_diemketthucmodulelan2);
                        break;
                }
                dgvDanhSachHocSinh.ShowEditor();
                btnHuyDiem.Enabled = true;
                btnXoaHocSinh.Enabled = false;
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void btnLuuDiem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                if (!mblnIsValid) return;

                float fltDiem;
                int intHsID;
                bool blnSuccess = true;
                DTO.THocSinhDiemTotNghiepDTO objHsMon;
                List<DTO.THocSinhDiemTotNghiepDTO> lstHsDiemTN;

                btnHuyDiem.Enabled = false;
                btnXoaHocSinh.Enabled = true;
                lstHsDiemTN = new List<DTO.THocSinhDiemTotNghiepDTO>();

                //lấy danh sách hs trc
                for (int i = 0; i <= dgvDanhSachHocSinh.RowCount - 1; i++)
                {
                    objHsMon = new DTO.THocSinhDiemTotNghiepDTO();

                    intHsID = clsCommon.fncCnvNullToInt(dgvDanhSachHocSinh.GetRowCellValue(i, colHS_ID));
                    objHsMon = DAO.THocSinhDiemTotNghiepDAO.Select(Program.gobjDb, intHsID, mintMonID, 1);

                    //chặn trg hợp nếu chưa có bản ghi nào
                    if (objHsMon == null)
                    {
                        objHsMon = new DTO.THocSinhDiemTotNghiepDTO();
                        objHsMon.HS_ID = intHsID;
                        objHsMon.Mon_ID = mintMonID;
                        objHsMon.LanThi_ID = 1;
                    }

                    switch (memLanThi)
                    {
                        case clsEnum.LAN_THI.LAN_1:
                            fltDiem = clsCommon.fncCnvNullToFloat(dgvDanhSachHocSinh.GetRowCellValue(i, colDiemLan1));
                            objHsMon.DiemLan1 = fltDiem;
                            break;
                        case clsEnum.LAN_THI.LAN_2:
                            fltDiem = clsCommon.fncCnvNullToFloat(dgvDanhSachHocSinh.GetRowCellValue(i, colDiemLan2));
                            objHsMon.DiemLan2 = fltDiem;
                            break;
                    }

                    lstHsDiemTN.Add(objHsMon);
                }

                Program.gobjTrans = Program.gobjConn.BeginTransaction();

                for (int i = 0; i <= lstHsDiemTN.Count - 1; i++)
                {
                    //thuc hien update bang cach xoa diem cu va them diem moi
                    //blnSuccess = DAO.THocSinhDiemTotNghiepDAO.Delete(Program.mobjDb, Program.mobjTrans, lstHsDiemTN[i].HS_ID, lstHsDiemTN[i].Mon_ID, lstHsDiemTN[i].LanThi_ID);
                    blnSuccess = DAO.THocSinhDiemTotNghiepDAO.Update(Program.gobjDb, Program.gobjTrans, lstHsDiemTN[i]);
                }

                if (blnSuccess)
                {
                    Program.gobjTrans.Commit();
                }
                else
                {
                    clsCommon.fncMsgError("Cập nhật thất bại. Xin hãy thử lại.");
                    Program.gobjTrans.Rollback();
                }

                switch (memLanThi)
                {
                    case clsEnum.LAN_THI.LAN_1:
                        colDiemLan1.OptionsColumn.AllowEdit = false;
                        break;
                    case clsEnum.LAN_THI.LAN_2:
                        colDiemLan2.OptionsColumn.AllowEdit = false;
                        break;
                }
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
            finally { Cursor.Current = Cursors.Default; }
        }

        private void btnXoaHocSinh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (dgvDanhSachHocSinh.FocusedRowHandle < 0) return;

                string strHodem = clsCommon.fncCnvNullToString(dgvDanhSachHocSinh.GetFocusedRowCellValue(colhs_hodem));
                string strTen = clsCommon.fncCnvNullToString(dgvDanhSachHocSinh.GetFocusedRowCellValue(colhs_ten));

                strTen = strHodem + " " + strTen;

                if (!clsCommon.fncMsgConfirm("Bạn có chắc muốn loại thí sinh " + strTen + " khỏi danh sách?")) return;

                int intHsID;

                intHsID = clsCommon.fncCnvNullToInt(dgvDanhSachHocSinh.GetFocusedRowCellValue(colHS_ID));

                if (!DAO.TThiTotNghiepHocSinhDAO.Delete(Program.gobjDb, Program.gobjTrans, mintTtnID, intHsID))
                {
                    //xóa thất bại
                    clsCommon.fncMsgError("Xóa thất bại. Xin hãy thử lại.");
                    return;
                }
                else
                {
                    dgvDanhSachHocSinh.DeleteSelectedRows();
                }

            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void btnHuyDiem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                btnHuyDiem.Enabled = false;
                btnXoaHocSinh.Enabled = true;
                this.usrProc_GetDanhSachThiTotNghiepTableAdapter.Fill(this.qLTHDataSet.usrProc_GetDanhSachThiTotNghiep, mintTtnID);
                dgvDanhSachHocSinh.BestFitColumns();
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void dgvDanhSachHocSinh_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            try
            {
                string strFieldName = "";

                switch (memLanThi)
                {
                    case clsEnum.LAN_THI.LAN_1:
                        strFieldName = "DiemLan1";
                        break;
                    case clsEnum.LAN_THI.LAN_2:
                        strFieldName = "DiemLan2";
                        break;
                }

                float fltDiem = 0.0F;

                if (!float.TryParse(dgvDanhSachHocSinh.GetRowCellValue(e.RowHandle, strFieldName).ToString(), out fltDiem))
                {
                    e.Valid = false;
                    dgvDanhSachHocSinh.SetColumnError(dgvDanhSachHocSinh.Columns[strFieldName], "Điểm không hợp lệ.");
                    mblnIsValid = false;
                    return;
                }

                if (fltDiem < 0 || fltDiem > 10)
                {
                    e.Valid = false;
                    dgvDanhSachHocSinh.SetColumnError(dgvDanhSachHocSinh.Columns[strFieldName], "Điểm không hợp lệ.");
                    mblnIsValid = false;
                    return;
                }

                mblnIsValid = true;

            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void dgvDanhSachHocSinh_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            try
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void btnXuatDanhSach_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if(mintTtnID <=0 )return;

                Cursor.Current = Cursors.WaitCursor;

                Export.frmExportExcel objForm = new Export.frmExportExcel();

                string strTrinhDo = "Cao đẳng";
                if(mintTrinhDo == (int)clsEnum.TRINH_DO_DAO_TAO.TRUNG_CAP) strTrinhDo = "Trung Cấp";
                if(mintTrinhDo == (int)clsEnum.TRINH_DO_DAO_TAO.SO_CAP) strTrinhDo = "Sơ Cấp";

                objForm.Text = string.Format("Danh sách thí sinh thi tốt nghiệp môn {0} khóa {1} {2} nghề {3}", clsCommon.fncCapitalizeFirst(mstrMon)
                                                                                                                , clsCommon.fncCapitalizeFirst(mstrKhoas)
                                                                                                                , clsCommon.fncCapitalizeFirst(strTrinhDo)
                                                                                                                , clsCommon.fncCapitalizeFirst(mstrNghe));
               
                if (!objForm.fncExportDanhSachThiTotNghiep(mintTtnID, mintTrinhDo)) return;
                objForm.MdiParent = this.MdiParent;
                objForm.Show();
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        private void mniDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (mintTtnID <= 0) return;

                if (dgvDanhSachHocSinh.RowCount > 0)
                {
                    clsCommon.fncMsgError("Vẫn tồn tại thí sinh trong danh sách. Chỉ có thể xóa khi trong danh sách không còn thí sinh nào.");
                    dgvDanhSachHocSinh.Focus();
                }


                Cursor.Current = Cursors.WaitCursor;
                                
                string strMessage = string.Format("Bạn có chắc muốn xóa môn {0} - thi lần {1} - lớp {2} - khóa {3}?", mstrMon, (int)memLanThi + 1, mstrLop, mstrKhoas);
                if (!clsCommon.fncMsgConfirm(strMessage)) return;

                DAO.MThiTotNghiepDAO.Delete(Program.gobjDb, Program.gobjTrans, mintTtnID);
                
                // TODO: This line of code loads data into the 'qLTHDataSet.usrProc_GetThiTotNghiepFull' table. You can move, or remove it, as needed.
                this.usrProc_GetThiTotNghiepFullTableAdapter.Fill(this.qLTHDataSet.usrProc_GetThiTotNghiepFull);
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
    }
}